import React, { useEffect, useRef, useState } from "react";
// import Markdown from "react-markdown";
import "./Note.css";
import MarkdownViewer from "./MarkdownViewer";
import MarkdownEditor from "./MarkdownEditor";
import "github-markdown-css";

interface ContentProps {
  content: string;
  setContent: React.Dispatch<React.SetStateAction<string>>;
  videoTimeStamp: number;
}

export default function Content({ content, setContent, videoTimeStamp }: ContentProps) {
  const [show, setShow] = useState(true);
  const containerRef = useRef();

  // 滚动条进度
  const [scrollTop, setScrollTop] = useState(0);

  function exit() {
    // 点击退出时记录文本框的滚动进度
    const mdEditor = document.getElementById("md-editor");
    if (mdEditor) {
      setScrollTop(mdEditor.scrollTop);
    }
    setShow(true);
  }

  // 更新预览框的滚动条进度
  useEffect(() => {
    const div = document.getElementById("divshow");
    if (div) {
      div.scrollTop = scrollTop;
    }
  }, [show, scrollTop]);

  function edit() {
    // 点击编辑时，记录预览框的滚动进度
    const div = document.getElementById("divshow");
    if (div) {
      setScrollTop(div.scrollTop);
    }
    setShow(false);
  }
  // 更新文本框的滚动进度
  useEffect(() => {
    const mdEditor = document.getElementById("md-editor");
    if (mdEditor) {
      mdEditor.scrollTop = scrollTop;
    }
  }, [show, scrollTop]);

  return (
    <>
      {show ? (
        <>
          <div ref={containerRef} className="NoteContent-container show markdown-body" id="divshow">
            <MarkdownViewer
              content={content}
              videoTimeStamp={videoTimeStamp}
              containerRef={containerRef}
              //   className="NoteContent-content"
            ></MarkdownViewer>
          </div>
          <input
            type="button"
            value=" 编辑 "
            onClick={edit}
            className="u-button edit_exit"
          ></input>
        </>
      ) : (
        <>
          <div className="NoteContent-container" id="md-editor">
            <MarkdownEditor value={content} onChange={setContent}></MarkdownEditor>
          </div>
          <input
            type="button"
            value=" 退出 "
            onClick={exit}
            className="u-button edit_exit"
          ></input>
        </>
      )}
    </>
  );
}
